package com.sj.security;

import cn.hutool.json.JSONUtil;
import com.sj.common.lang.ApiResultMsg;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021-08-02
 * Time: 下午 15:08
 * Description: 权限不足处理器
 * @author xiaoqi
 */
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {


    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");

        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        ServletOutputStream outputStream = response.getOutputStream();
        ApiResultMsg resultMsg = ApiResultMsg.error(HttpServletResponse.SC_FORBIDDEN, "权限不足");
        outputStream.write(JSONUtil.toJsonStr(resultMsg).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}